import matplotlib.pyplot as plt
from celluloid import Camera
import numpy as np

def bubble_sort_visual(arr):
    fig = plt.figure(figsize=(10, 6))
    camera = Camera(fig)
    
    n = len(arr)
    for i in range(n):
        for j in range(0, n-i-1):
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]
            # 绘制当前状态
            bars = plt.bar(range(len(arr)), arr, color='skyblue')
            plt.title(f'冒泡排序 - 第 {i+1} 轮, 第 {j+1} 次比较')
            # 在每个柱子上方添加元素值
            for bar in bars:
                height = bar.get_height()
                plt.text(bar.get_x() + bar.get_width()/2., height,
                        f'{int(height)}',
                        ha='center', va='bottom')
            camera.snap()
    
    animation = camera.animate()
    animation.save('冒泡排序动画.gif', writer='pillow', fps=2)
    print("冒泡排序动画.gif 已成功生成")

# 测试数据
test_array = [64, 34, 25, 12, 22, 11, 90]
bubble_sort_visual(test_array)